package conversion.Interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import conversion.bean.User;
import conversion.utils.JwtUtil;
import conversion.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {

//    @Resource
//    JwtUtil jwtUtil;

    @Resource
    JwtUtils jwtUtils;

    @Resource
    ObjectMapper objectMapper;

    /**
     * 目标方法执行之前
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        String requestURI = request.getRequestURI();
        log.info("preHandle拦截的请求路径是{}",requestURI);

        HttpSession session = request.getSession();
        // 检查是否包含 token
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("token")) {
                    String token = cookie.getValue();
                    // 验证 token 的合法性
                    boolean isValidToken = jwtUtils.verifyToken(token);
                    if (isValidToken) {
                        // 从 token 中获取用户信息
                        String userInfo = jwtUtils.getUserInfo(token);
                        User user = objectMapper.readValue(userInfo, User.class);
                        if (user != null) {
                            // 将用户信息放入 session
                            session.setAttribute("user", user);
                            //如果你已登录还行访问登录页面，则进行拦截
                            if("/login".equals(requestURI)){
                                response.sendRedirect("/index");
                            }
                            // 放行
                            log.info("放行");
                            return true;
                        }
                    }
                }
            }
        }

        String[] excludePathPatterns = {"/","/index","/login","/account/login"};

        //循环放行请求
        for (String excludePathPattern : excludePathPatterns) {
            //判断是否为放行路径
            if (excludePathPattern.equals(requestURI)){
                log.info("已放行");
                return true;
            }
        }

        //当没有token，并且访问不开放请求时，进行拦截，跳转到登录页面
        request.setAttribute("msg","请先登录");
        log.info("拦截");

        session.setAttribute("requestURI",requestURI);

        response.sendRedirect("/login");
        return false;
    }

//    /**
//     * 目标方法执行完成以后
//     */
//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        log.info("postHandle执行{}",modelAndView);
//    }
//
//    /**
//     * 页面渲染以后
//     */
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        log.info("afterCompletion执行异常{}",ex);
//    }
}
